//
//  FavoriteService.swift
//  hello
//
//  Created by 赵康 on 2025/4/15.
//

import Vapor
import Fluent

struct FavoriteService {
  let logger: Logger
  
  init(logger: Logger = Logger(label: "com.bayanarabic.favoriteService")) {
    self.logger = logger
  }
  
  // 创建收藏
  func createFavorite(userID: UUID, albumID: UUID, req: Request) async throws -> BasicResponse {
    logger.info("开始创建收藏: userID=\(userID), albumID=\(albumID)")
    return try await req.db.transaction { transaction in
      // 检查专辑是否存在
      guard let album = try await Album.find(albumID, on: transaction) else {
        logger.info("创建收藏失败: 专辑不存在, albumID=\(albumID)")
        throw Abort(.notFound, reason: "专辑不存在")
      }
      
      // 检查是否已收藏
      let existingFavorite = try await Favorite.query(on: transaction)
        .filter(\.$user.$id == userID)
        .filter(\.$album.$id == albumID)
        .filter(\.$isDeleted == false)
        .first()
      
      if existingFavorite != nil {
        logger.info("创建收藏失败: 专辑已收藏, userID=\(userID), albumID=\(albumID)")
        throw Abort(.badRequest, reason: "专辑已收藏")
      }
      
      // 创建新收藏
      let favorites = Favorite(
        userID: userID,
        albumID: albumID,
        isDeleted: false,
        createdAt: Date(),
        updatedAt: Date()
      )
      try await favorites.save(on: transaction)
      logger.info("新收藏记录已创建, favoriteID=\(favorites.id?.uuidString ?? "unknown")")
      
      // 创建或获取默认收藏夹
      let defaultFolder = try await getOrCreateDefaultFolder(userID: userID, on: transaction)
      logger.info("获取到默认收藏夹: folderID=\(defaultFolder.id?.uuidString ?? "unknown")")
      
      // 将收藏添加到默认文件夹
      favorites.$folder.id = defaultFolder.id!
      try await favorites.save(on: transaction)
      logger.info("收藏已添加到默认收藏夹")
      
      // 更新专辑收藏计数, 确保最小值为零
      album.favoriteCount = max(0, album.favoriteCount + 1)
      try await album.save(on: transaction)
      logger.info("专辑收藏计数已更新: 新计数=\(album.favoriteCount)")
      
      logger.info("收藏创建成功: userID=\(userID), albumID=\(albumID)")
      return BasicResponse(success: true, message: "收藏成功")
    }
  }
  
  // 删除收藏
  func deleteFavorite(userID: UUID, albumID: UUID, req: Request) async throws -> BasicResponse {
    logger.info("开始删除收藏: userID=\(userID), albumID=\(albumID)")
    return try await req.db.transaction { transaction in
      guard let album = try await Album.find(albumID, on: transaction) else {
        logger.info("删除收藏失败: 专辑不存在, albumID=\(albumID)")
        throw Abort(.notFound, reason: "专辑不存在")
      }
      
      guard let favorite = try await Favorite.query(on: transaction)
        .filter(\.$user.$id == userID)
        .filter(\.$album.$id == albumID)
        .filter(\.$isDeleted == false)
        .first() else {
        logger.info("删除收藏失败: 专辑未收藏, userID=\(userID), albumID=\(albumID)")
        throw Abort(.notFound, reason: "专辑未收藏")
      }
      
      favorite.isDeleted = true
      favorite.updatedAt = Date()
      try await favorite.save(on: transaction)
      logger.info("收藏记录已标记为删除: favoriteID=\(favorite.id?.uuidString ?? "unknown")")
      
      // 更新专辑收藏计数, 确保最小值为零
      album.favoriteCount = max(0, album.favoriteCount - 1)
      try await album.save(on: transaction)
      logger.info("专辑收藏计数已更新: 新计数=\(album.favoriteCount)")
      
      logger.info("收藏删除成功: userID=\(userID), albumID=\(albumID)")
      return BasicResponse(success: true, message: "取消收藏成功")
    }
  }
  
  // 获取收藏列表
  func fetchFavorites(userID: UUID, req: Request) async throws -> [AlbumResponse] {
    logger.info("开始获取收藏列表: userID=\(userID)")
    // 系统专辑ID
    let systemAlbumID = UUID(uuidString: "00000000-0000-0000-0000-000000000000")!
    
    // 查询数据库
    let favorites = try await Favorite.query(on: req.db)
      .filter(\.$user.$id == userID)
      .filter(\.$isDeleted == false)
      .filter(\.$album.$id != systemAlbumID) // 过滤掉系统专辑
      .with(\.$album) { album in
        album.with(\.$tags)
      }
      .all()
    
    logger.info("查询到收藏记录: count=\(favorites.count)")
    
    // 将查询结果转换为响应数据模型
    let albumResponses = favorites.map { favorite in
      let album = favorite.album
      return AlbumResponse(
        id: album.id,
        title: album.title,
        description: album.description,
        cover: album.cover,
        audioCount: album.audioCount,
        playCount: album.playCount,
        favoriteCount: album.favoriteCount,
        wordCount: album.wordCount,
        category: album.category,
        isFavorite: true,
        tags: album.tags.map { tag in
          TagResponse(id: tag.id, name: tag.name)
        },
        createdAt: album.createdAt,
        updatedAt: album.updatedAt
      )
    }
    
    logger.info("收藏列表获取成功: userID=\(userID), count=\(albumResponses.count)")
    return albumResponses
  }
  
  // 获取或创建默认收藏夹
  private func getOrCreateDefaultFolder(userID: UUID, on db: Database) async throws -> Folder {
    logger.info("尝试获取默认收藏夹: userID=\(userID)")
    if let defaultFolder = try await Folder.query(on: db)
      .filter(\.$user.$id == userID)
      .filter(\.$isDefault == true)
      .first() {
      logger.info("找到现有默认收藏夹: folderID=\(defaultFolder.id?.uuidString ?? "unknown")")
      return defaultFolder
    }
    
    logger.info("未找到默认收藏夹，开始创建")
    // 创建默认收藏夹
    let defaultFolder = Folder(
      name: "默认收藏夹",
      isDefault: true,
      userID: userID
    )
    
    try await defaultFolder.save(on: db)
    logger.info("已创建新的默认收藏夹: folderID=\(defaultFolder.id?.uuidString ?? "unknown")")
    return defaultFolder
  }
  
  // 获取用户所有收藏夹
  func fetchFolders(userID: UUID, req: Request) async throws -> [FolderResponse] {
    logger.info("开始获取用户收藏夹列表: userID=\(userID)")
    let folders = try await Folder.query(on: req.db)
      .filter(\.$user.$id == userID)
      .sort(\.$position, .ascending)
      .all()
    
    logger.info("查询到收藏夹记录: count=\(folders.count)")
    
    var folderResponses: [FolderResponse] = []
    
    for folder in folders {
      // 获取每个收藏夹中的专辑数量
      let albumCount = try await Favorite.query(on: req.db)
        .filter(\.$folder.$id == folder.id!)
        .filter(\.$user.$id == userID)
        .filter(\.$isDeleted == false)
        .count()
      
      logger.info("收藏夹 '\(folder.name)' (ID=\(folder.id!)) 包含专辑数量: \(albumCount)")
      
      folderResponses.append(FolderResponse(
        id: folder.id!,
        name: folder.name,
        isDefault: folder.isDefault,
        createdAt: folder.createdAt,
        albumCount: albumCount
      ))
    }
    
    logger.info("收藏夹列表获取成功: userID=\(userID), count=\(folderResponses.count)")
    return folderResponses
  }
  
  // 创建收藏夹
  func createFolder(userID: UUID, name: String, isDefault: Bool? = nil, req: Request) async throws -> FolderResponse {
    logger.info("开始创建收藏夹: userID=\(userID), name=\(name), isDefault=\(isDefault ?? false)")
    return try await req.db.transaction { transaction in
      // 检查是否已存在同名收藏夹
      if try await Folder.query(on: transaction)
        .filter(\.$user.$id == userID)
        .filter(\.$name == name)
        .first() != nil {
        logger.info("创建收藏夹失败: 已存在同名收藏夹, name=\(name)")
        throw Abort(.badRequest, reason: "已存在同名收藏夹")
      }
      
      let folder = Folder(
        name: name,
        isDefault: isDefault ?? false,
        userID: userID
      )
      
      try await folder.save(on: transaction)
      logger.info("收藏夹创建成功: folderID=\(folder.id?.uuidString ?? "unknown"), name=\(name)")
      
      return FolderResponse(
        id: folder.id!,
        name: folder.name,
        isDefault: folder.isDefault,
        createdAt: folder.createdAt,
        albumCount: 0
      )
    }
  }
  
  // 重命名收藏夹
  func renameFolder(userID: UUID, folderID: UUID, newName: String, req: Request) async throws -> FolderResponse {
    logger.info("开始重命名收藏夹: userID=\(userID), folderID=\(folderID), newName=\(newName)")
    return try await req.db.transaction { transaction in
      guard let folder = try await Folder.query(on: transaction)
        .filter(\.$id == folderID)
        .filter(\.$user.$id == userID)
        .first() else {
        logger.info("重命名收藏夹失败: 收藏夹不存在, folderID=\(folderID)")
        throw Abort(.notFound, reason: "收藏夹不存在")
      }
      
      logger.info("找到收藏夹: folderID=\(folderID), 当前名称=\(folder.name)")
      
      // 检查是否已存在同名收藏夹
      if try await Folder.query(on: transaction)
        .filter(\.$user.$id == userID)
        .filter(\.$name == newName)
        .filter(\.$id != folderID)
        .first() != nil {
        logger.info("重命名收藏夹失败: 已存在同名收藏夹, newName=\(newName)")
        throw Abort(.badRequest, reason: "已存在同名收藏夹")
      }
      
      folder.name = newName
      folder.updatedAt = Date()
      try await folder.save(on: transaction)
      logger.info("收藏夹重命名成功: folderID=\(folderID), 新名称=\(newName)")
      
      // 获取收藏夹中的专辑数量
      let albumCount = try await Favorite.query(on: transaction)
        .filter(\.$folder.$id == folderID)
        .filter(\.$user.$id == userID)
        .filter(\.$isDeleted == false)
        .count()
      
      logger.info("收藏夹包含专辑数量: \(albumCount)")
      
      return FolderResponse(
        id: folder.id!,
        name: folder.name,
        isDefault: folder.isDefault,
        createdAt: folder.createdAt,
        albumCount: albumCount
      )
    }
  }
  
  // 删除收藏夹
  func deleteFolder(userID: UUID, folderID: UUID, req: Request) async throws -> BasicResponse {
    logger.info("开始删除收藏夹: userID=\(userID), folderID=\(folderID)")
    return try await req.db.transaction { transaction in
      guard let folder = try await Folder.query(on: transaction)
        .filter(\.$id == folderID)
        .filter(\.$user.$id == userID)
        .first() else {
        logger.info("删除收藏夹失败: 收藏夹不存在, folderID=\(folderID)")
        throw Abort(.notFound, reason: "收藏夹不存在")
      }
      
      logger.info("找到收藏夹: folderID=\(folderID), name=\(folder.name), isDefault=\(folder.isDefault)")
      
      // 不能删除默认收藏夹
      if folder.isDefault {
        logger.info("删除收藏夹失败: 默认收藏夹不能删除")
        throw Abort(.badRequest, reason: "默认收藏夹不能删除")
      }
      
      // 获取此收藏夹下的所有收藏
      let favorites = try await Favorite.query(on: transaction)
        .filter(\.$folder.$id == folderID)
        .filter(\.$user.$id == userID)
        .filter(\.$isDeleted == false)
        .all()
      
      logger.info("收藏夹中找到的收藏记录数量: \(favorites.count)")
      
      // 取消收藏所有专辑
      for favorite in favorites {
        favorite.isDeleted = true
        favorite.updatedAt = Date()
        try await favorite.save(on: transaction)
        logger.info("已标记收藏为删除: favoriteID=\(favorite.id?.uuidString ?? "unknown"), albumID=\(favorite.$album.id)")
        
        // 更新专辑收藏计数
        if let album = try await Album.find(favorite.$album.id, on: transaction) {
          album.favoriteCount = max(0, album.favoriteCount - 1)
          try await album.save(on: transaction)
          logger.info("更新专辑收藏计数: albumID=\(album.id?.uuidString ?? "unknown"), 新计数=\(album.favoriteCount)")
        }
      }
      
      // 删除收藏夹
      try await folder.delete(on: transaction)
      logger.info("收藏夹删除成功: folderID=\(folderID)")
      
      return BasicResponse(success: true, message: "删除收藏夹成功")
    }
  }
  
  // 添加专辑到收藏夹
  func addAlbumToFolder(userID: UUID, albumID: UUID, folderID: UUID, req: Request) async throws -> BasicResponse {
    logger.info("开始添加专辑到收藏夹: userID=\(userID), albumID=\(albumID), folderID=\(folderID)")
    return try await req.db.transaction { transaction in
      // 检查收藏夹是否存在
      guard let folder = try await Folder.query(on: transaction)
        .filter(\.$id == folderID)
        .filter(\.$user.$id == userID)
        .first() else {
        logger.info("添加专辑到收藏夹失败: 收藏夹不存在, folderID=\(folderID)")
        throw Abort(.notFound, reason: "收藏夹不存在")
      }
      
      logger.info("找到收藏夹: folderID=\(folderID), name=\(folder.name)")
      
      // 检查专辑是否已收藏
      guard let favorite = try await Favorite.query(on: transaction)
        .filter(\.$user.$id == userID)
        .filter(\.$album.$id == albumID)
        .filter(\.$isDeleted == false)
        .first() else {
        // 如果专辑还未收藏，先创建收藏
        let album = try await Album.find(albumID, on: transaction)
        guard album != nil else {
          logger.info("添加专辑到收藏夹失败: 专辑不存在, albumID=\(albumID)")
          throw Abort(.notFound, reason: "专辑不存在")
        }
        
        logger.info("专辑未被收藏，创建新收藏: albumID=\(albumID)")
        
        let newFavorite = Favorite(
          userID: userID,
          albumID: albumID,
          folderID: folderID,
          isDeleted: false,
          createdAt: Date(),
          updatedAt: Date()
        )
        try await newFavorite.save(on: transaction)
        logger.info("已创建新收藏并添加到指定收藏夹: favoriteID=\(newFavorite.id?.uuidString ?? "unknown")")
        
        // 更新专辑收藏计数
        album!.favoriteCount = max(0, album!.favoriteCount + 1)
        try await album!.save(on: transaction)
        logger.info("更新专辑收藏计数: albumID=\(albumID), 新计数=\(album!.favoriteCount)")
        
        return BasicResponse(success: true, message: "专辑已添加到收藏夹")
      }
      
      logger
        .info(
          "找到现有收藏记录: favoriteID=\(favorite.id?.uuidString ?? "unknown"), 当前folderID=\(String(describing: favorite.$folder.id))"
        )
      
      // 更新收藏的文件夹ID
      favorite.$folder.id = folderID
      try await favorite.save(on: transaction)
      logger.info("收藏记录已更新到新收藏夹: favoriteID=\(favorite.id?.uuidString ?? "unknown"), 新folderID=\(folderID)")
      
      return BasicResponse(success: true, message: "专辑已添加到收藏夹")
    }
  }
  
  // 从收藏夹移除专辑
  func removeAlbumFromFolder(userID: UUID, folderID: UUID, albumID: UUID, req: Request) async throws -> BasicResponse {
    logger.info("开始从收藏夹移除专辑: userID=\(userID), folderID=\(folderID), albumID=\(albumID)")
    return try await req.db.transaction { transaction in
      // 检查收藏夹是否存在
      guard let folder = try await Folder.query(on: transaction)
        .filter(\.$id == folderID)
        .filter(\.$user.$id == userID)
        .first() else {
        logger.info("从收藏夹移除专辑失败: 收藏夹不存在, folderID=\(folderID)")
        throw Abort(.notFound, reason: "收藏夹不存在")
      }
      
      logger.info("找到收藏夹: folderID=\(folderID), name=\(folder.name)")
      
      // 检查专辑是否在此收藏夹中
      guard let favorite = try await Favorite.query(on: transaction)
        .filter(\.$user.$id == userID)
        .filter(\.$album.$id == albumID)
        .filter(\.$folder.$id == folderID)
        .filter(\.$isDeleted == false)
        .first() else {
        logger.info("从收藏夹移除专辑失败: 专辑不在此收藏夹中, albumID=\(albumID), folderID=\(folderID)")
        throw Abort(.notFound, reason: "专辑不在此收藏夹中")
      }
      
      logger.info("找到收藏记录: favoriteID=\(favorite.id?.uuidString ?? "unknown")")
      
      // 无论是否为默认收藏夹，都取消收藏
      favorite.isDeleted = true
      favorite.updatedAt = Date()
      try await favorite.save(on: transaction)
      logger.info("收藏记录已标记为删除")
      
      // 更新专辑收藏计数
      let album = try await Album.find(albumID, on: transaction)
      if let album = album {
        album.favoriteCount = max(0, album.favoriteCount - 1)
        try await album.save(on: transaction)
        logger.info("更新专辑收藏计数: albumID=\(albumID), 新计数=\(album.favoriteCount)")
      }
      
      logger.info("专辑已从收藏夹移除: albumID=\(albumID), folderID=\(folderID)")
      return BasicResponse(success: true, message: "已从收藏夹移除专辑")
    }
  }
  
  // 获取收藏夹内的专辑
  func getAlbumsInFolder(userID: UUID, folderID: UUID, sortOrder: FavoritesSortOrder? = nil, req: Request) async throws -> [AlbumResponse] {
    logger.info("开始获取收藏夹内专辑: userID=\(userID), folderID=\(folderID), sortOrder=\(sortOrder?.rawValue ?? "默认")")
    // 检查收藏夹是否存在
    guard let folder = try await Folder.query(on: req.db)
      .filter(\.$id == folderID)
      .filter(\.$user.$id == userID)
      .first() else {
      logger.info("获取收藏夹内专辑失败: 收藏夹不存在, folderID=\(folderID)")
      throw Abort(.notFound, reason: "收藏夹不存在")
    }
    
    logger.info("找到收藏夹: folderID=\(folderID), name=\(folder.name)")
    
    // 获取用户的排序偏好
    let preferenceString = try await getSortPreference(userID: userID, folderID: folderID, req: req)
    let effectiveSortOrder: FavoritesSortOrder
    
    // 优先检查是否是自定义排序
    if let preferenceString = preferenceString, preferenceString == FavoritesSortOrder.custom.rawValue {
      // 如果是自定义排序，无论请求参数如何，都使用自定义排序
      effectiveSortOrder = .custom
      logger.info("用户设置了自定义排序，忽略请求参数，使用自定义排序")
    } else if let sortOrder = sortOrder {
      // 如果提供了排序参数，且用户没有设置自定义排序，使用请求参数
      effectiveSortOrder = sortOrder
    } else if let preferenceString = preferenceString, let preference = FavoritesSortOrder(rawValue: preferenceString) {
      // 如果有保存的排序偏好（非自定义），使用保存的偏好
      effectiveSortOrder = preference
    } else {
      // 默认排序
      effectiveSortOrder = .titleAsc
    }
    
    logger.info("使用排序方式: \(effectiveSortOrder.rawValue)")
    
    // 获取收藏夹内的所有收藏
    var query = Favorite.query(on: req.db)
      .filter(\.$folder.$id == folderID)
      .filter(\.$user.$id == userID)
      .filter(\.$isDeleted == false)
      .with(\.$album) { album in
        album.with(\.$tags)
      }
    
    // 如果是使用自定义顺序，则按position排序
    if effectiveSortOrder == .custom {
      query = query.sort(\.$position, .ascending)
    }
    
    // 查询结果
    let favorites = try await query.all()
    logger.info("查询到收藏记录: count=\(favorites.count)")
    
    // 将收藏转换为专辑响应模型
    var albumResponses = favorites.map { favorite in
      let album = favorite.album
      return AlbumResponse(
        id: album.id,
        title: album.title,
        description: album.description,
        cover: album.cover,
        audioCount: album.audioCount,
        playCount: album.playCount,
        favoriteCount: album.favoriteCount,
        wordCount: album.wordCount,
        category: album.category,
        isFavorite: true,
        tags: album.tags.map { tag in
          TagResponse(id: tag.id, name: tag.name)
        },
        createdAt: album.createdAt,
        updatedAt: album.updatedAt
      )
    }
    
    // 根据排序选项排序（除了自定义排序，因为自定义排序已经在查询时处理）
    if effectiveSortOrder != .custom {
      logger.info("应用排序选项: \(effectiveSortOrder.rawValue)")
      albumResponses = sortAlbums(albumResponses, by: effectiveSortOrder)
    }
    
    logger.info("收藏夹内专辑获取成功: folderID=\(folderID), 专辑数量=\(albumResponses.count)")
    return albumResponses
  }
  
  // 根据排序选项排序专辑
  private func sortAlbums(_ albums: [AlbumResponse], by sortOrder: FavoritesSortOrder) -> [AlbumResponse] {
    logger.info("排序专辑列表: 排序方式=\(sortOrder.rawValue), 专辑数量=\(albums.count)")
    switch sortOrder {
      case .titleAsc:
        return albums.sorted { $0.title < $1.title }
      case .titleDesc:
        return albums.sorted { $0.title > $1.title }
      case .playCountHighToLow:
        return albums.sorted { $0.playCount > $1.playCount }
      case .playCountLowToHigh:
        return albums.sorted { $0.playCount < $1.playCount }
      case .audioCountHighToLow:
        return albums.sorted { $0.audioCount > $1.audioCount }
      case .audioCountLowToHigh:
        return albums.sorted { $0.audioCount < $1.audioCount }
      case .dateAddedNewest:
        return albums.sorted { ($0.createdAt ?? Date.distantPast) > ($1.createdAt ?? Date.distantPast) }
      case .dateAddedOldest:
        return albums.sorted { ($0.createdAt ?? Date.distantPast) < ($1.createdAt ?? Date.distantPast) }
      case .custom:
        // 自定义排序不在这里处理，而是在查询时通过position排序
        return albums
    }
  }
  
  // 更新收藏夹排序
  func updateFoldersOrder(userID: UUID, folderOrders: [FolderOrderItem], req: Request) async throws -> BasicResponse {
    logger.info("开始更新收藏夹排序: userID=\(userID), 收藏夹数量=\(folderOrders.count)")
    return try await req.db.transaction { transaction in
      for folderOrder in folderOrders {
        guard let folder = try await Folder.query(on: transaction)
          .filter(\.$id == folderOrder.id)
          .filter(\.$user.$id == userID)
          .first() else {
          logger.warning("更新收藏夹排序: 找不到收藏夹, folderID=\(folderOrder.id)")
          continue
        }
        
        folder.position = folderOrder.position
        try await folder.save(on: transaction)
        logger.info("收藏夹顺序已更新: folderID=\(folderOrder.id), position=\(folderOrder.position)")
      }
      
      logger.info("收藏夹排序更新完成")
      return BasicResponse(success: true, message: "收藏夹排序已更新")
    }
  }
  
  // 更新收藏夹内专辑排序
  func updateAlbumsOrder(userID: UUID, folderID: UUID, albumOrders: [AlbumOrderItem], req: Request) async throws -> BasicResponse {
    logger.info("开始更新收藏夹内专辑排序: userID=\(userID), folderID=\(folderID), 专辑数量=\(albumOrders.count)")
    return try await req.db.transaction { transaction in
      // 检查收藏夹是否存在
      guard let folder = try await Folder.query(on: transaction)
        .filter(\.$id == folderID)
        .filter(\.$user.$id == userID)
        .first() else {
        logger.error("更新专辑排序失败: 收藏夹不存在, folderID=\(folderID)")
        throw Abort(.notFound, reason: "收藏夹不存在")
      }
      
      logger.info("找到收藏夹: folderID=\(folderID), name=\(folder.name)")
      
      for albumOrder in albumOrders {
        // 查找对应的收藏记录
        guard let favorite = try await Favorite.query(on: transaction)
          .filter(\.$user.$id == userID)
          .filter(\.$folder.$id == folderID)
          .filter(\.$album.$id == albumOrder.id)
          .filter(\.$isDeleted == false)
          .first() else {
          logger.warning("更新专辑排序: 找不到收藏记录, albumID=\(albumOrder.id)")
          continue
        }
        
        favorite.position = albumOrder.position
        try await favorite.save(on: transaction)
        logger.info("专辑排序已更新: albumID=\(albumOrder.id), position=\(albumOrder.position)")
      }
      
      logger.info("收藏夹内专辑排序更新完成")
      
      // 更新排序偏好为 custom
      let existingPreference = try await UserSortPreference.query(on: transaction)
        .filter(\.$user.$id == userID)
        .filter(\.$folder.$id == folderID)
        .first()
      
      if let existingPreference = existingPreference {
        logger.info("更新排序偏好为 custom")
        existingPreference.sortOrder = FavoritesSortOrder.custom.rawValue
        try await existingPreference.save(on: transaction)
      } else {
        logger.info("创建新的排序偏好记录，设置为 custom")
        let preference = UserSortPreference(
          userID: userID,
          folderID: folderID,
          sortOrder: FavoritesSortOrder.custom.rawValue
        )
        try await preference.save(on: transaction)
      }
      
      // 清除相关缓存
      try await FavoriteCache(req: req).clearUserFavoriteCache(userID: userID, on: req)
      
      return BasicResponse(success: true, message: "专辑排序已更新")
    }
  }
  
  // 保存用户排序偏好
  func saveSortPreference(userID: UUID, folderID: UUID, sortOrder: String, req: Request) async throws -> BasicResponse {
    logger.info("开始保存用户排序偏好: userID=\(userID), folderID=\(folderID), sortOrder=\(sortOrder)")
    return try await req.db.transaction { transaction in
      // 检查收藏夹是否存在
      guard let _ = try await Folder.query(on: transaction)
        .filter(\.$id == folderID)
        .filter(\.$user.$id == userID)
        .first() else {
        logger.error("保存排序偏好失败: 收藏夹不存在, folderID=\(folderID)")
        throw Abort(.notFound, reason: "收藏夹不存在")
      }
      
      // 查找现有的排序偏好
      let existingPreference = try await UserSortPreference.query(on: transaction)
        .filter(\.$user.$id == userID)
        .filter(\.$folder.$id == folderID)
        .first()
      
      if let existingPreference = existingPreference {
        logger.info("找到现有排序偏好记录, 进行更新")
        existingPreference.sortOrder = sortOrder
        try await existingPreference.save(on: transaction)
      } else {
        logger.info("创建新的排序偏好记录")
        let preference = UserSortPreference(
          userID: userID,
          folderID: folderID,
          sortOrder: sortOrder
        )
        try await preference.save(on: transaction)
      }
      
      logger.info("排序偏好保存成功")
      
      // 清除相关缓存
      try await FavoriteCache(req: req).clearUserFavoriteCache(userID: userID, on: req)
      
      return BasicResponse(success: true, message: "排序偏好已保存")
    }
  }
  
  // 获取用户排序偏好
  func getSortPreference(userID: UUID, folderID: UUID, req: Request) async throws -> String? {
    logger.info("获取用户排序偏好: userID=\(userID), folderID=\(folderID)")
    
    let preference = try await UserSortPreference.query(on: req.db)
      .filter(\.$user.$id == userID)
      .filter(\.$folder.$id == folderID)
      .first()
    
    if let preference = preference {
      logger.info("找到用户排序偏好: sortOrder=\(preference.sortOrder)")
      return preference.sortOrder
    }
    
    logger.info("未找到用户排序偏好, 返回默认值")
    return nil
  }
}

